import React, { useEffect, useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import TextArea from '@/components/Textarea'
import { useSelector } from 'react-redux'
import { error } from '@/utils/tools'
import { User } from '@/types/user'
type EditInputProps = {
  onLeftClick?: () => void
  type: 'name' | 'intro'
  onCommit: (a: object) => void
}
export default function EditInput({
  onLeftClick,
  type,
  onCommit,
}: EditInputProps) {
  // 从redux中获取用户自己的信息
  const user = useSelector(
    (state: { profile: { user: User } }) => state.profile
  ).user
  // 定义昵称数据
  const [nickname, setNickname] = useState(user.name)
  // 定义介绍数据
  const [intro, setIntro] = useState(user.intro)

  // 获取焦点的控制数据
  const [inputFocus, setInputFocus] = useState(false)
  const [textareaFocus, setTextareaFocus] = useState(false)

  useEffect(() => {
    type === 'name' ? setInputFocus(true) : setInputFocus(false)
    type === 'intro' ? setTextareaFocus(true) : setTextareaFocus(false)
  }, [type])

  // 提交数据
  const onClickHandler = () => {
    // 数据验证
    if (type === 'name' && nickname!.trim().length === 0) {
      return error('昵称不能修改为空')
    }
    if (type === 'intro' && intro!.trim().length === 0) {
      return error('自我介绍不能为空')
    }
    // 触发父组件的提交事件
    onCommit({
      [type]: type === 'name' ? nickname : intro,
    })
  }

  return (
    <div className={styles.root}>
      <NavBar
        extra={
          <span className="commit-btn" onClick={onClickHandler}>
            提交
          </span>
        }
        className="navbar"
        onLeftClick={onLeftClick}
      >
        {type === 'name' ? '编辑昵称' : '编辑简介'}
      </NavBar>
      <div className="content-box">
        <h3> {type === 'name' ? '昵称' : '简介'}</h3>
        {/* 文本输入框和文本域 */}
        {type === 'name' ? (
          <Input
            onChange={(e) => setNickname(e.target.value)}
            focus={inputFocus}
            value={nickname}
            className="input-wrap"
          />
        ) : (
          <TextArea
            focus={textareaFocus}
            className="intro"
            value={intro!}
            placeholder="请输入简介"
            maxLength={20}
            onChange={(e) => setIntro(e.target.value)}
          />
        )}
      </div>
    </div>
  )
}
